(function($) {
	$.fn.tabsy = function() {
		this.addClass("tabsy-container");
		f = this;
		tab = $('<div class="tabsy-tab main active">Main</div>').click(function(){
			if ($(this).hasClass('active')) return;
			c = $(this).attr('class').split(' ')[1];
			activate(f, c);
		});
		header = $('<div class="tabsy-header"></div>').append(tab);
		main_tab = make_window(f, 'main active', this.html());
		this.html(header).append(main_tab);
	}
	function make_window(obj, stamp, contents) {
		tab = $('<div class="tabsy-window ' + stamp + '"></div>').append(contents);
		if ($(tab).find("a").size() == 0) return tab;
		$(tab).find("a").click(function(e){
			e.preventDefault();
			tab_name = $(this).find(".tabsy-name").html();
			link = $(this).attr('href');
			add_tab(obj, tab_name, link);
		});
		return tab;
	}
	function add_tab(obj, tab_name, link) {
		stamp = tab_name.toLowerCase().split(' ').join('-');
		if ($(obj).find(".tabsy-tab."+stamp).size() != 0) {
			n = 1;
			while ($(obj).find(".tabsy-tab."+stamp+n).size() != 0) n += 1;
			stamp = stamp+n;
		}
		new_tab = $('<div class="tabsy-tab ' + stamp + '">'+tab_name+'</div>').click(function(){
			if ($(this).hasClass('active')) return;
			c = $(this).attr('class').split(' ')[1];
			activate(obj, c);
		});
		$(obj).find(".tabsy-header").append(new_tab);
		$.get(link, function(contents){
			tab = make_window(obj, stamp, contents);
			$(obj).append(tab);
			activate(obj, stamp);
		},'html');
	}
	function activate(obj, stamp) {
		$(obj).find(".tabsy-tab.active").removeClass('active');
		$(obj).find(".tabsy-window.active").removeClass('active');
		$(obj).find(".tabsy-tab."+stamp).addClass('active');
		$(obj).find(".tabsy-window."+stamp).addClass('active');
	}
}(jQuery));
